const ip = /*"http://localhost:8080" + */"/zhh";

// 发送GET请求
 function sendGetRequest(url, data = null, async = true) {
    return sendRequest('GET', url, data, async);
}

// 发送POST请求
 function sendPostRequest(url,  data = null, async = true) {
    return sendRequest('POST', url, data);
}


 function sendRequest(method, url, data = null, async = true) {
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open(method, ip + url, async);

        if (method === 'POST') {
            xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        }

        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    let response = JSON.parse(xhr.responseText);
                    if (response.code !== 200) {
                        reject(new Error(response.message));
                    }
                    resolve(response.data);
                } catch (e) {
                    resolve(xhr.responseText);
                }
            } else {
                reject(new Error(`Request failed with status: ${xhr.status}`));
            }
        };

        xhr.onerror = function () {
            reject(new Error('Request failed'));
        };

        if (method === 'POST') {
            xhr.send(JSON.stringify(data));
        } else {
            xhr.send();
        }
    });
}
